#include "systemtraymanager.h"
#include "mainwindow.h"
#include "versionmanager.h"
#include <QApplication>
#include <QPixmap>
#include <QPainter>
#include <QFontMetrics>
#include <QDesktopServices>
#include <QUrl>
#include <QDebug>

SystemTrayManager::SystemTrayManager(QObject* parent)
    : QObject(parent)
    , m_trayIcon(nullptr)
    , m_contextMenu(nullptr)
    , m_showAction(nullptr)
    , m_updateAction(nullptr)
    , m_downloadAction(nullptr)
    , m_separator1(nullptr)
    , m_separator2(nullptr)
    , m_quitAction(nullptr)
    , m_mainWindow(nullptr)
    , m_updateManager(nullptr)
    , m_isDownloading(false)
    , m_downloadProgress(0)
    , m_downloadedBytes(0)
    , m_totalBytes(0)
    , m_progressTimer(new QTimer(this))
    , m_initialized(false)
    , m_updateAvailable(false)
{

    // 创建UpdateManager
    m_updateManager = new UpdateManager(this);

    // 连接UpdateManager信号
    connect(m_updateManager, &UpdateManager::updateAvailable,
            this, &SystemTrayManager::onUpdateAvailable);
    connect(m_updateManager, &UpdateManager::downloadProgress,
            this, &SystemTrayManager::onDownloadProgress);
    connect(m_updateManager, &UpdateManager::downloadFinished,
            this, &SystemTrayManager::onDownloadFinished);
    connect(m_updateManager, &UpdateManager::downloadError,
            this, &SystemTrayManager::onDownloadError);

    // 创建应用图标
    m_appIcon = QIcon(":/icons/app.png");
    if (m_appIcon.isNull()) {
        // 如果没有图标文件，创建一个简单的默认图标
        QPixmap pixmap(32, 32);
        pixmap.fill(QColor("#007aff"));
        m_appIcon = QIcon(pixmap);
    }

    // 创建下载图标（带进度条的应用图标）
    m_downloadIcon = m_appIcon;
}

SystemTrayManager::~SystemTrayManager()
{
}

void SystemTrayManager::initialize()
{
    if (m_initialized) {
        return;
    }


    if (!QSystemTrayIcon::isSystemTrayAvailable()) {
        return;
    }

    setupTrayIcon();
    setupContextMenu();

    m_initialized = true;
}

bool SystemTrayManager::isSystemTrayAvailable() const
{
    return QSystemTrayIcon::isSystemTrayAvailable() && m_initialized;
}

void SystemTrayManager::show()
{
    if (m_trayIcon && m_initialized) {
        m_trayIcon->show();
    }
}

void SystemTrayManager::hide()
{
    if (m_trayIcon) {
        m_trayIcon->hide();
    }
}

void SystemTrayManager::setMainWindow(QWidget* mainWindow)
{
    m_mainWindow = mainWindow;
}

void SystemTrayManager::onUpdateDownloadStarted()
{

    m_isDownloading = true;
    m_downloadProgress = 0;
    m_downloadedBytes = 0;
    m_totalBytes = 0;

    updateTrayIcon(true);
    updateTrayTooltip(tr("正在下载更新... 0%"));

    // 更新下载菜单项
    if (m_downloadAction) {
        m_downloadAction->setText(tr("暂停下载"));
        m_downloadAction->setEnabled(true);
    }

    // 显示通知
    showNotification(tr("开始下载"), tr("正在下载最新版本..."));
}

void SystemTrayManager::onDownloadProgress(int progress, qint64 received, qint64 total)
{
    if (!m_isDownloading) {
        m_isDownloading = true;
        onUpdateDownloadStarted();
    }

    m_downloadProgress = progress;
    m_downloadedBytes = received;
    m_totalBytes = total;

    QString tooltip = formatProgress(progress, received, total);
    updateTrayTooltip(tooltip);

}

void SystemTrayManager::onDownloadFinished(const QString& filePath)
{

    m_isDownloading = false;
    m_downloadProgress = 100;
    m_downloadedBytes = m_totalBytes;

    updateTrayIcon(false);
    updateTrayTooltip(tr("下载完成！点击安装更新"));

    // 更新下载菜单项
    if (m_downloadAction) {
        m_downloadAction->setText(tr("安装更新"));
        m_downloadAction->setEnabled(true);
    }

    // 显示完成通知
    showNotification(tr("下载完成"), tr("更新已下载完成，点击安装"));

    m_updateAvailable = true;
}

void SystemTrayManager::onDownloadError(const QString& error)
{

    m_isDownloading = false;
    m_downloadProgress = 0;

    updateTrayIcon(false);
    updateTrayTooltip(tr("下载失败：%1").arg(error));

    // 更新下载菜单项
    if (m_downloadAction) {
        m_downloadAction->setText(tr("重试下载"));
        m_downloadAction->setEnabled(true);
    }

    // 显示错误通知
    showNotification(tr("下载失败"), error);
}

void SystemTrayManager::onUpdateAvailable(const VersionManager::UpdateInfo& info)
{

    m_currentUpdateInfo = info;
    m_updateAvailable = true;

    updateTrayTooltip(tr("发现新版本 %1").arg(info.latestVersion.toString()));

    // 更新更新菜单项
    if (m_updateAction) {
        QString updateText = tr("更新到 %1").arg(info.latestVersion.toString());
        m_updateAction->setText(updateText);
        m_updateAction->setEnabled(true);
    }

    // 显示更新通知
    if (info.forceUpdate) {
        showNotification(tr("重要更新"), tr("必须更新到版本 %1").arg(info.latestVersion.toString()));
    } else {
        showNotification(tr("发现新版本"), tr("版本 %1 现已可用").arg(info.latestVersion.toString()));
    }
}

void SystemTrayManager::showUpdateDialog()
{
    if (!m_updateAvailable || m_currentUpdateInfo.latestVersion.major == 0) {
        return;
    }

    // 创建更新对话框
    UpdateDialog* updateDialog = new UpdateDialog(m_currentUpdateInfo, nullptr);

    // 连接信号
    connect(updateDialog, &UpdateDialog::requestStartDownload,
            m_updateManager, &UpdateManager::startUpdate);
    connect(updateDialog, &UpdateDialog::requestPauseDownload,
            m_updateManager, &UpdateManager::pauseDownload);

    // 连接进度信号
    connect(m_updateManager, &UpdateManager::downloadProgress,
            updateDialog, &UpdateDialog::onDownloadProgress);
    connect(m_updateManager, &UpdateManager::downloadFinished,
            updateDialog, &UpdateDialog::onDownloadFinished);
    connect(m_updateManager, &UpdateManager::downloadError,
            updateDialog, &UpdateDialog::onDownloadError);

    updateDialog->setAttribute(Qt::WA_DeleteOnClose);
    updateDialog->show();

}

void SystemTrayManager::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason) {
    case QSystemTrayIcon::Trigger:
    case QSystemTrayIcon::DoubleClick:
        // 左键点击显示主窗口
        showMainWindow();
        break;
    case QSystemTrayIcon::MiddleClick:
        // 中键点击检查更新
        checkForUpdates();
        break;
    case QSystemTrayIcon::Context:
        // 右键显示上下文菜单（自动处理）
        break;
    default:
        break;
    }
}

void SystemTrayManager::showMainWindow()
{
    if (m_mainWindow) {
        m_mainWindow->show();
        m_mainWindow->raise();
        m_mainWindow->activateWindow();
    }
}

void SystemTrayManager::quitApplication()
{
    QApplication::quit();
}

void SystemTrayManager::checkForUpdates()
{
    if (m_updateManager) {
        m_updateManager->checkForUpdates();
    }
}

void SystemTrayManager::toggleDownload()
{
    if (m_isDownloading) {
        if (m_updateManager) {
            m_updateManager->pauseDownload();
        }
    } else if (m_updateAvailable) {
        if (m_downloadAction && m_downloadAction->text() == tr("安装更新")) {
            // 打开下载的文件进行安装
            if (m_updateManager) {
                QString downloadPath = m_updateManager->getDownloadPath();
                if (!downloadPath.isEmpty()) {
                    QDesktopServices::openUrl(QUrl::fromLocalFile(downloadPath));
                }
            }
        } else {
            // 开始下载
            if (m_updateManager) {
                m_updateManager->startUpdate();
            }
        }
    }
}

void SystemTrayManager::setupTrayIcon()
{
    if (!m_trayIcon) {
        m_trayIcon = new QSystemTrayIcon(this);
    }

    // 设置图标
    updateTrayIcon(false);

    // 设置提示
    updateTrayTooltip(tr("LimeReader - 长图阅读专家"));

    // 连接激活信号
    connect(m_trayIcon, &QSystemTrayIcon::activated,
            this, &SystemTrayManager::onTrayIconActivated);

}

void SystemTrayManager::setupContextMenu()
{
    if (!m_contextMenu) {
        m_contextMenu = new QMenu();
    }

    // 清除现有动作
    m_contextMenu->clear();

    // 显示主窗口
    m_showAction = new QAction(tr("显示主窗口"), this);
    connect(m_showAction, &QAction::triggered, this, &SystemTrayManager::showMainWindow);
    m_contextMenu->addAction(m_showAction);

    m_contextMenu->addSeparator();

    // 检查更新
    m_updateAction = new QAction(tr("检查更新"), this);
    connect(m_updateAction, &QAction::triggered, this, &SystemTrayManager::checkForUpdates);
    m_contextMenu->addAction(m_updateAction);

    // 下载/暂停/安装动作
    m_downloadAction = new QAction(tr("下载更新"), this);
    m_downloadAction->setEnabled(false);
    connect(m_downloadAction, &QAction::triggered, this, &SystemTrayManager::toggleDownload);
    m_contextMenu->addAction(m_downloadAction);

    m_contextMenu->addSeparator();

    // 退出
    m_quitAction = new QAction(tr("退出"), this);
    connect(m_quitAction, &QAction::triggered, this, &SystemTrayManager::quitApplication);
    m_contextMenu->addAction(m_quitAction);

    // 设置上下文菜单
    m_trayIcon->setContextMenu(m_contextMenu);

}

void SystemTrayManager::updateTrayIcon(bool downloading)
{
    if (!m_trayIcon) {
        return;
    }

    if (downloading && m_downloadProgress > 0 && m_downloadProgress < 100) {
        // 创建带进度条的图标
        QPixmap pixmap = m_appIcon.pixmap(32, 32);
        QPainter painter(&pixmap);

        // 绘制进度条背景
        painter.setPen(Qt::NoPen);
        painter.setBrush(QColor(0, 0, 0, 100));
        painter.drawRect(2, 28, 28, 4);

        // 绘制进度条
        painter.setBrush(QColor(0, 122, 255));
        int progressWidth = 28 * m_downloadProgress / 100;
        painter.drawRect(2, 28, progressWidth, 4);

        QIcon progressIcon(pixmap);
        m_trayIcon->setIcon(progressIcon);
    } else {
        m_trayIcon->setIcon(m_appIcon);
    }
}

void SystemTrayManager::updateTrayTooltip(const QString& tooltip)
{
    if (m_trayIcon) {
        m_trayIcon->setToolTip(tooltip);
    }
}

void SystemTrayManager::showNotification(const QString& title, const QString& message)
{
    if (m_trayIcon && QSystemTrayIcon::supportsMessages()) {
        m_trayIcon->showMessage(title, message, QSystemTrayIcon::Information, 5000);
    }
}

QString SystemTrayManager::formatProgress(int progress, qint64 received, qint64 total) const
{
    if (total > 0) {
        QString receivedStr = formatFileSize(received);
        QString totalStr = formatFileSize(total);
        return tr("正在下载... %1% (%2/%3)").arg(progress).arg(receivedStr).arg(totalStr);
    } else {
        return tr("正在下载... %1%").arg(progress);
    }
}

QString SystemTrayManager::formatFileSize(qint64 bytes) const
{
    if (bytes < 1024) {
        return QString("%1 B").arg(bytes);
    } else if (bytes < 1024 * 1024) {
        return QString("%1 KB").arg(bytes / 1024.0, 0, 'f', 1);
    } else if (bytes < 1024 * 1024 * 1024) {
        return QString("%1 MB").arg(bytes / (1024.0 * 1024.0), 0, 'f', 1);
    } else {
        return QString("%1 GB").arg(bytes / (1024.0 * 1024.0 * 1024.0), 0, 'f', 1);
    }
}